import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:tracker/common/widget/common.dart';
import 'package:tracker/pages/home/vip_service/mixin/other_service_mixin.dart';
import 'package:tracker/pages/home/vip_service/mixin/vip_service_mixin.dart';
import 'package:tracker/pages/home/vip_service/model/vip_service_list_resp.dart';

import '../../../../provider/global_provider.dart';
import '../../../../theme/app_theme.dart';

class OtherRecord extends ConsumerStatefulWidget {
  final int index;

  const OtherRecord({super.key, required this.index});

  @override
  ConsumerState<OtherRecord> createState() => _OtherRecordState();
}

class _OtherRecordState extends ConsumerState<OtherRecord>
    with OtherServiceMixin, VipServicePageMixin, AutomaticKeepAliveClientMixin {
  bool showLoading = true;

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      actionType = widget.index;
      getPackageList(actionType + 1).then((value) {
        if (actionType == 1) {
          highVipServiceData.clear();
          highVipServiceData.addAll(value.data ?? []);
        } else {
          recordVipServiceData.clear();
          recordVipServiceData.addAll(value.data ?? []);
        }
        showLoading = false;
        setState(() {});
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return showLoading
        ? Container(
            alignment: Alignment.center,
            child: CircularProgressIndicator(
              color: AppTheme.themeConfig.primaryColor,
            ),
          )
        : (getVipData().isNotEmpty ? buildBody() : const Center());
  }

  Widget buildBody() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(height: 12),
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.only(bottom: 16),
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) {
                if (index == getVipData().length) {
                  return _buildServiceContent();
                }
                return buildVip(index);
              },
              separatorBuilder: (context, index) {
                return const SizedBox(height: 12);
              },
              itemCount: getVipData().length + 1,
            ),
          ),
          _buildPaymentSection(),
          _buildPayButton(),
        ],
      ),
    );
  }

  Widget _buildServiceContent() {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(6),
                decoration: BoxDecoration(
                  color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  Icons.description,
                  color: AppTheme.themeConfig.primaryColor,
                  size: 16,
                ),
              ),
              const SizedBox(width: 8),
              Text(
                "服务内容",
                style: TextStyle(
                  color: AppTheme.themeConfig.primaryTextColor,
                  fontSize: 15,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: AppTheme.themeConfig.greyBgColor,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Text(
              getVipData()[getSelectIndex()].content ?? "",
              style: TextStyle(
                color: AppTheme.themeConfig.secondaryTextColor,
                fontSize: 14,
                height: 1.5,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentSection() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.payment,
                color: AppTheme.themeConfig.primaryColor,
                size: 18,
              ),
              const SizedBox(width: 8),
              Text(
                "支付方式",
                style: TextStyle(
                  color: AppTheme.themeConfig.primaryTextColor,
                  fontSize: 15,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: buildContainer(
                  title: "支付宝",
                  image: "assets/images/pay/alipay_logo.png",
                  index: 0,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: buildContainer(
                  title: "微信",
                  image: "assets/images/pay/wxpay_logo.png",
                  index: 1,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPayButton() {
    return Container(
      margin: const EdgeInsets.only(bottom: 20),
      child: GestureDetector(
        onTap: payVip,
        child: Container(
          height: 56,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [
                AppTheme.themeConfig.primaryColor,
                AppTheme.themeConfig.primaryColor.withOpacity(0.8),
              ],
            ),
            borderRadius: BorderRadius.circular(28),
            boxShadow: [
              BoxShadow(
                color: AppTheme.themeConfig.primaryColor.withOpacity(0.4),
                blurRadius: 12,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(
                Icons.shopping_cart,
                color: Colors.white,
                size: 22,
              ),
              const SizedBox(width: 12),
              Text(
                "确认并支付 ¥${getVipData()[getSelectIndex()].price}",
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 17,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void payVip() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (actionType == 1) {
      if (highPayIndex == 0) {
        alipayUtils.createVip(
            highVipServiceData[highIndex].packageId?.toInt(),
            deviceInfo.imei.toString());
      } else {
        wxpayUtils.createVip(
            highVipServiceData[highIndex].packageId?.toInt(),
            deviceInfo.imei.toString(), highVipServiceData[highIndex].price?.toDouble());
      }
    } else {
      if (recordPayIndex == 0) {
        alipayUtils.createVip(
            recordVipServiceData[recordIndex].packageId?.toInt(),
            deviceInfo.imei.toString());
      } else {
        wxpayUtils.createVip(
            recordVipServiceData[recordIndex].packageId?.toInt(),
            deviceInfo.imei.toString(), recordVipServiceData[recordIndex].price?.toDouble());
      }
    }

  }

  Widget buildContainer(
      {required String image, required String title, required int index}) {
    final isSelected = getPayIndex() == index;
    return GestureDetector(
      onTap: () {
        setState(() {
          if (actionType == 1) {
            highPayIndex = index;
          } else {
            recordPayIndex = index;
          }
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          gradient: isSelected
              ? LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    AppTheme.themeConfig.primaryColor.withOpacity(0.15),
                    AppTheme.themeConfig.primaryColor.withOpacity(0.05),
                  ],
                )
              : null,
          color: isSelected ? null : AppTheme.themeConfig.greyBgColor,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isSelected
                ? AppTheme.themeConfig.primaryColor
                : Colors.grey.shade300,
            width: isSelected ? 2 : 1,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(image, width: 24, height: 24),
            const SizedBox(width: 8),
            Text(
              title,
              style: TextStyle(
                fontSize: 14,
                fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                color: isSelected
                    ? AppTheme.themeConfig.primaryColor
                    : AppTheme.themeConfig.primaryTextColor,
              ),
            ),
            if (isSelected) ...[
              const SizedBox(width: 6),
              Icon(
                Icons.check_circle,
                color: AppTheme.themeConfig.primaryColor,
                size: 18,
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget buildVip(int index) {
    VipServiceData data = getVipData()[index];
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: AppTheme.themeConfig.primaryColor.withOpacity(0.3),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 6,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: Text(
              data.title ?? "",
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: AppTheme.themeConfig.primaryColor,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          const SizedBox(width: 16),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisSize: MainAxisSize.min,
            children: [
              RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: "¥",
                      style: TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 16,
                        color: AppTheme.themeConfig.primaryColor,
                      ),
                    ),
                    TextSpan(
                      text: "${data.price}",
                      style: TextStyle(
                        fontWeight: FontWeight.w900,
                        fontSize: 28,
                        color: AppTheme.themeConfig.primaryColor,
                      ),
                    ),
                  ],
                ),
              ),
              Text(
                "元",
                style: TextStyle(
                  fontSize: 13,
                  color: AppTheme.themeConfig.primaryColor,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
